package com.wwwarehouse.contract.contract.publishgoods;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.contract.bean.ResourceItemBean;
import com.wwwarehouse.contract.bean.SaveRulesBean;
import com.wwwarehouse.contract.bean.SettingRuleBean;
import com.wwwarehouse.contract.contract.MyBaseViewPagerFragment;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.event.DeleteSettingRuleEvent;
import com.wwwarehouse.contract.event.NotifyDeleteEvent;
import com.wwwarehouse.contract.event.OperationEvent;
import com.wwwarehouse.contract.event.PublishingRulesEvent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

/**
 * @author Joseph on 2017/10/19.
 *         <p/>
 *         设置发布规则
 */

public class SettingPublishingRulesFragment extends MyBaseViewPagerFragment {

    private String pbUkid;
    private String sort;
    private Bundle bundle;
    private SettingRuleBean.DataBean dataBean;
    private String title = "";
    private List<ResourceItemBean.DataBean.ListBean> select;
    private SettingRuleBean.DataBean.ListBean msg;
    boolean hasSetRule = true;

    @Override
    public void setTitle() {
        if (peekFragment() instanceof SettingPublishingRulesFragment) {
            mActivity.setTitle(title);
        }
    }

    @Override
    protected void loadDatas() {
        mConfirmBtn.setVisibility(View.VISIBLE);
        mConfirmBtn.setText(R.string.release);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            pbUkid = getArguments().getString("pbUkid");
            sort = getArguments().getString("sort");
            select = (List<ResourceItemBean.DataBean.ListBean>) getArguments().getSerializable("selectList");
        }
        mActivity.setTitle(getString(R.string.set_release_rule));
        bundle = new Bundle();
        bundle.putString("pbUkid", pbUkid);
        bundle.putString("sort", sort);

        requestData();


        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<SettingRuleBean.DataBean.ListBean> selectTag = getSelectTag();

                for (int i = 0; i < selectTag.size(); i++) {
                    if (!selectTag.get(i).isHasSetRule()) {
                        toast(getString(R.string.contract_setting_rules_tips));
                        hasSetRule = false;
                        break;
                    } else {
                        hasSetRule = true;
                    }
                }

                if (hasSetRule) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("pbUkid", pbUkid);
                    List<SaveRulesBean> pbRsItemTempList = new ArrayList<>();
                    for (int i = 0; i < selectTag.size(); i++) {
                        SaveRulesBean saveRulesBean = new SaveRulesBean();
                        SettingRuleBean.DataBean.ListBean bean = selectTag.get(i);
                        saveRulesBean.setBarCode(bean.getBarCode());
                        saveRulesBean.setUnit(bean.getUnit());
                        saveRulesBean.setDefinedUkid(bean.getDefinedUkid());
                        saveRulesBean.setImg(bean.getImg());
                        saveRulesBean.setName(bean.getName());
                        saveRulesBean.setPbPrice(bean.getPbPrice());
                        saveRulesBean.setPbQty(bean.getPbQty());
                        saveRulesBean.setPbQtyUnit(bean.getPbQtyUnit());
                        saveRulesBean.setPbQtyUnitUkid(bean.getPbQtyUnitUkid());
                        saveRulesBean.setPriceRuleType(bean.getPriceRuleType());
                        saveRulesBean.setPriceRuleValue(bean.getPriceRuleValue());
                        saveRulesBean.setQtyRuleType(bean.getQtyRuleType());
                        saveRulesBean.setQtyRuleValue(bean.getQtyRuleValue());
                        saveRulesBean.setSoldNum(bean.getSize());
                        saveRulesBean.setPrice(bean.getPrice()+"");
                        saveRulesBean.setQty(bean.getQty());
                        saveRulesBean.setUnit(bean.getUnit());
                        pbRsItemTempList.add(saveRulesBean);
                    }
                    map.put("pbRsItemTempList", pbRsItemTempList);

                    httpPost(ContractConstant.SAVEADDRESOURCEITEMANDRULE, map, 1, true, "");
                }
            }
        });
    }

    //获取选择的数据集合
    private List<SettingRuleBean.DataBean.ListBean> getSelectTag() {
        List<SettingRuleBean.DataBean.ListBean> selectDatas = new ArrayList<>();
        for (int i = 0; i < fragmentList.size(); i++) {
            if (fragmentList.get(i) != null) {
                SettingRulesGoodsListFragment currentFragment = (SettingRulesGoodsListFragment) fragmentList.get(i);
                List<SettingRuleBean.DataBean.ListBean> settingrulesData = currentFragment.getSettingrulesData();
                selectDatas.addAll(settingrulesData);
            }
        }
        return selectDatas;
    }


    private void requestData() {
        Map<String, Object> map = new HashMap<>();
        map.put("page", "1"); //
        map.put("pbUkid", pbUkid); //  发布ukid
        map.put("size", 9999); //
        map.put("sort", sort); //     排序(DESC,ASC)
        httpPost(ContractConstant.GETPBRSITEMTEMPSBYPBUKID, map, 0, true, "");
    }

    @Override
    public void onSuccess(CommonClass commonClass, int what) {
        if (what == 1) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                popFragment();
                popFragment();
                PublishingRulesEvent publishingRulesEvent = new PublishingRulesEvent(getSelectTag(),select);
                EventBus.getDefault().post(publishingRulesEvent);
            } else {
                toast(getString(R.string.contract_setting_rules_tips));
            }
        } else if (what == 0) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                dataBean = JSON.parseObject(commonClass.getData().toString(), SettingRuleBean.DataBean.class);
                if (dataBean.getTotal() != 0 || select.size() != 0) {
                    mConfirmBtn.setVisibility(View.VISIBLE);
                    showViewPagerView();
                    title = getString(R.string.set_release_rule) + "(" + (dataBean.getTotal() + select.size()) + ")";
                    mActivity.setTitle(title);
                    setViewPager();
                } else if (dataBean.getTotal() == 0 && select.size() == 0) {

                    title = getString(R.string.set_release_rule);
                    mActivity.setTitle(title);
                    mConfirmBtn.setVisibility(View.GONE);
                    ShowEmptyView(getString(R.string.contract_nodata));


                }
            } else {
                toast(commonClass.getMsg());
            }

        } else if (what == 2) {
            if (TextUtils.equals("0", commonClass.getCode())) {
                EventBus.getDefault().post(new NotifyDeleteEvent(msg.getDefinedUkid()));
                requestData();

            } else {
                toast(commonClass.getMsg());
            }

        }

    }

    private void setViewPager() {
        List<SettingRuleBean.DataBean.ListBean> list = dataBean.getList();
        if (list == null) {
            list = new ArrayList<>();
        }
        for (int i = 0; i < select.size(); i++) {
            SettingRuleBean.DataBean.ListBean bean = new SettingRuleBean.DataBean.ListBean();
            bean.setDefinedUkid(select.get(i).getDefinedUkid() + "");
            bean.setSelectListData(true);
            try {
                bean.setImg(select.get(i).getMediaList().get(0).getRelatedUrl());
            } catch (Exception e) {
                bean.setImg("");
            }
            bean.setName(select.get(i).getDefinedName());
            //选择商品暂无字段
            bean.setPrice(0);
            bean.setPbQtyUnit(select.get(i).getUnitName());
            bean.setPbQtyUnitUkid(select.get(i).getUnitUkid()+"");
            bean.setUnit(select.get(i).getUnitName());
            try {
                bean.setBarCode(select.get(i).getIdentifyList().get(0).getIdentifyCode());
            } catch (Exception e) {
                bean.setBarCode("");
            }
            list.add(bean);
        }
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setHasSetRule(!TextUtils.isEmpty(list.get(i).getPriceRuleType()) || !TextUtils.isEmpty(list.get(i).getQtyRuleType()));
        }


        bundle.putSerializable("settingRuleData", (Serializable) list);
        bundle.putSerializable("selectList", (Serializable) select);
        SetFragmentAndPage(dataBean.getTotal() + select.size(), 5, new SettingRulesGoodsListFragment().getClass().getName(), bundle);
    }

    public void onEventMainThread(Object event) {
        if (event instanceof DeleteSettingRuleEvent) {
            msg = ((DeleteSettingRuleEvent) event).getMsg();
            boolean selectListData = msg.isSelectListData();
            if (selectListData) {
                for (int i = 0; i < select.size(); i++) {
                    if (((DeleteSettingRuleEvent) event).getMsg().getDefinedUkid().equals(select.get(i).getDefinedUkid() + "")) {
                        EventBus.getDefault().post(new OperationEvent(select.get(i), "deleteAndRefersh"));
                        select.remove(i);
                        if (dataBean.getTotal() != 0 || select.size() != 0) {
                            title = getString(R.string.set_release_rule) + "(" + (dataBean.getTotal() + select.size()) + ")";
                            mActivity.setTitle(title);
                            showViewPagerView();
                            mConfirmBtn.setVisibility(View.VISIBLE);
                            setViewPager();
                        } else {
                            title = getString(R.string.set_release_rule);
                            mActivity.setTitle(title);
                            mConfirmBtn.setVisibility(View.GONE);
                            ShowEmptyView(getString(R.string.contract_nodata));
                        }

                        break;
                    }
                }

            } else {
                Map<String, Object> map = new HashMap<>();
                map.put("itemTempUkid", msg.getItemTempUkid()); //
                httpPost(ContractConstant.DELETEPBRSITEMTEMP, map, 2, true, "");
            }


        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
